package controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import dao.DormitoryDao;
import dao.DormroomsDao;
import dao.DormscoresDao;
import dao.impl.DormitoryDaoImpl;
import dao.impl.DormroomsDaoImpl;
import dao.impl.DormscoresDaoImpl;
import entity.Dormitory;
import entity.Dormrooms;
import entity.Dorm_scores;
import service.DormitoryService;
import service.DormroomsService;
import service.DormscoresService;
import service.impl.DormitoryServiceImpl;
import service.impl.DormroomsServiceImpl;
import service.impl.DormscoresServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/dormscoresController")
public class DormscoresController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        String op = req.getParameter("op");
        PrintWriter out = resp.getWriter();
        if (op.equals("cxj")) {
            // 查询宿舍评分列表（分页）
            String lid = req.getParameter("lid");
            String pageStr = req.getParameter("page");
            int page = StringUtils.isNullOrEmpty(pageStr) ? 0 : Integer.parseInt(pageStr);
            int pageSize = 5; // 每页5条记录
            DormscoresDao dsd = new DormscoresDaoImpl();
            List<Dorm_scores> list = null;
            int totalCount = 0;
            try {
                Integer lidParam = StringUtils.isNullOrEmpty(lid) ? null : Integer.valueOf(lid);
                totalCount = dsd.getTotalCount(lidParam);
                int totalPages = (totalCount + pageSize - 1) / pageSize;
                page = Math.max(0, Math.min(page, totalPages - 1));
                list = dsd.cxj(lidParam, page, pageSize);
                Map<String, Object> result = new HashMap<>();
                result.put("list", list);
                result.put("page", page);
                result.put("totalPages", totalPages);
                result.put("totalCount", totalCount);
                out.write(JSON.toJSONString(result));
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                out.write("查询失败：" + e.getMessage());
            }
        }else if (op.equals("scj")) {
            DormscoresDao dsd = new DormscoresDaoImpl();
            try {
                String dormId = req.getParameter("id");
                if (dormId != null && !dormId.isEmpty()) {
                    int isSuccess = dsd.scj(Integer.parseInt(dormId));

                    // 添加删除结果响应
                    if (isSuccess > 0) {
                        out.write("删除成功");
                    } else {
                        out.write("删除失败，记录不存在");
                    }
                    List<Dorm_scores> list = dsd.cx3(0);
                    session.setAttribute("list", list);
                } else {
                    out.write("宿舍ID不能为空");
                }
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                out.write("删除失败：" + e.getMessage());
            }
        }else if (op.equals("add3")){
            String room_id=req.getParameter("roomId");
            String check_date=req.getParameter("checkDate");
            String hygiene_score=req.getParameter("hygieneScore");
            String discipline_score=req.getParameter("disciplineScore");
            String  inspector=req.getParameter("inspector");

            if(room_id ==null||room_id.isEmpty()|| check_date == null|| check_date.isEmpty() || hygiene_score==null|| hygiene_score.isEmpty()|| discipline_score ==null||discipline_score.isEmpty() || inspector ==null||inspector.isEmpty()){
                out.write("所有字段不能为空");
                return;
            }
            DormscoresDao dsd=new DormscoresDaoImpl();
            try {
                if(dsd.cx1(room_id)>0){
                dsd.tjj(dsd.cx1(room_id),check_date,Integer.parseInt(hygiene_score),Integer.parseInt(discipline_score),inspector);
                out.write("添加成功");
                }else {
                    out.write("房间不存在");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                out.write("添加失败" + e.getMessage());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                out.write("添加失败" + e.getMessage());
            } catch (NumberFormatException e) {
                out.write("参数格式错误");
            }
        }else if (op.equals("update3")) {
            // 接收前端发送的参数
            String scoreId=req.getParameter("scoreId");
            String roomId = req.getParameter("roomId");
            String checkDate = req.getParameter("checkDate");
            String hygieneScore = req.getParameter("hygieneScore");
            String disciplineScore = req.getParameter("disciplineScore");
            String inspector = req.getParameter("inspector");
            DormscoresDao dsd = new DormscoresDaoImpl();
            try {
                // 调用修改方法，使用roomId作为条件更新宿舍信息
                int success = dsd.xgj( Integer.parseInt(scoreId),  Integer.parseInt(roomId), checkDate, Integer.parseInt(hygieneScore),Integer.parseInt(disciplineScore), inspector);
                if (success > 0) {
                    out.write("修改成功");
                } else {
                    out.write("修改失败，记录不存在");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                out.write("修改失败，数据库错误");
            } catch (NumberFormatException | ClassNotFoundException e) {
                e.printStackTrace();
                out.write("修改失败，参数格式错误");
            }
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}